package com.zh.demo02.util;

import java.util.Random;

/**
 * 生成随机验证码
 * @author ZH
 * @Date 12:44 2020/4/15
 */
public class RandomCodeUtil {

    /**
     * 生成随机数字验证码
     * @param len 字符长度，不能超出1-20范围
     * @return
     */
    public static String getNumberCode(int len){
        if (len>20 || len<1)
            throw new RuntimeException("len 不符合1-20的长度要求");

        Random random = new Random();
        char[] arr = new char[len];
        for(int i=0; i<len; i++){
            arr[i] = (char)(48+random.nextInt(10));
        }
        return String.valueOf(arr);
    }

    /**
     * 生成随机验证码
     * @param len 字符长度，不能超出1-20范围
     * @return
     */
    public static String getCharacterCode(int len){
        if (len>20 || len<1)
            throw new RuntimeException("len 不符合1-20的长度要求");

        char[] numberCharacters = {'2','3','4','5','6','7','8'};

        Random random = new Random();
        char[] arr = new char[len];
        for(int i=0; i<len; i++){
            //65-89表示(A-Y), 90-96表示numberCharacters
            int index = ('A'+random.nextInt(25+numberCharacters.length))%('A'+25);
            if (index>='A'){
                arr[i] = (char)index;
            }else{
                arr[i] = numberCharacters[index];
            }
        }
        return String.valueOf(arr);
    }
}
